package net.jcip.chapter5;

import java.util.Scanner;
import java.util.Vector;

/**
 * SafeVectorHelpers
 * <p/>
 * Compound actions on Vector using client-side locking
 *
 * @author Brian Goetz and Tim Peierls
 */
public class SafeVectorHelpers {


    private static Object getLast(Vector list) {
        synchronized (list) {
            int lastIndex = list.size() - 1;
            return  list.get(lastIndex) ;
        }
    }

    private static void deleteLast(Vector list) {
        synchronized (list) {
            int lastIndex = list.size() - 1;
            Object obj = list.remove(lastIndex);
            System.out.println("WARN  被删除的元素是 " + obj );
        }
    }



    /**
     * 验证
     * */
    public static void main(String[] args) throws InterruptedException {

        Vector<Integer> vector = new Vector<>(100);

        for (int i = 0; i < 100; i++) {
            vector.add(i) ;
        }

        Thread getThread = new Thread(() -> {

            for (int i = 0; i < vector.size(); i++) {
                Integer  obj = (Integer) SafeVectorHelpers.getLast(vector);
                System.out.println("INFO  顶头元素是 " + obj);
            }

        }, "get线程");


        Thread deleteThread = new Thread(() -> {

            for (int i = 0; i < 100; i++) {

                SafeVectorHelpers.deleteLast(vector);
            }

        }, "delete线程");

        getThread.start();
        deleteThread.start();

        Scanner scanner = new Scanner(System.in);
        System.out.println("任意键退出.....\n");
        scanner.next();


    }

}
